package com.asd.netty.netty.server;


import com.asd.netty.netty.common.PacketProto;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;

/**
 * @author LRL
 */
@Service
public class ServerHeartbeatInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ServerHeartbeatHandler serverHeartbeatHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(PacketProto.Packet.getDefaultInstance()));
        pipeline.addLast(new IdleStateHandler(6, 0, 0));
        pipeline.addLast(new ServerHeartbeatHandler());

        // 解码器
        // 基于换行符号
        socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));

        // 解码转String
        socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));

        // 编码器 String
        socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));

        // 在管道中添加我们自己的接收数据实现方法
        socketChannel.pipeline().addLast(serverHeartbeatHandler);
    }
}
